package com.unipay.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.unipay.common.handler.UnipayException;
import com.unipay.common.result.ResultCodeEnum;
import com.unipay.hosp.repository.ScheduleRepository;
import com.unipay.hosp.service.DepartmentService;
import com.unipay.hosp.service.HospitalService;
import com.unipay.hosp.service.ScheduleService;
import com.unipay.model.hosp.BookingRule;
import com.unipay.model.hosp.Department;
import com.unipay.model.hosp.Hospital;
import com.unipay.model.hosp.Schedule;
import com.unipay.vo.hosp.ScheduleOrderVo;
import com.unipay.vo.hosp.ScheduleQueryVo;
import com.unipay.yygh.vo.hosp.BookingScheduleRuleVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-04-07 19:22:47
 * @Desc: TODO
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> paramObjMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramObjMap), Schedule.class);
        Schedule scheduleByHoscodeAndHosScheduleId = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (null != scheduleByHoscodeAndHosScheduleId) {
            scheduleByHoscodeAndHosScheduleId.setUpdateTime(new Date());
            scheduleRepository.deleteById(schedule.getId());
            scheduleRepository.save(scheduleByHoscodeAndHosScheduleId);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(0);
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectSchedulePage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //（1）分页插件
        Sort createTimeSort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, createTimeSort);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        //（2）创建匹配器，即如何使用查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //（3）创建实例
        Example<Schedule> scheduleExample = Example.of(schedule, exampleMatcher);
        Page<Schedule> schedulePage = scheduleRepository.findAll(scheduleExample, pageable);
        return schedulePage;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule scheduleByHoscodeAndHosScheduleId = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (scheduleByHoscodeAndHosScheduleId != null) {
            scheduleRepository.deleteById(scheduleByHoscodeAndHosScheduleId.getId());
        }
    }

    //TODO mongoDB 聚合操作
    //根据hoscode 和 depcode ，查询 schedule规则数据
    @Override
    public Map<String, Object> getPageSchedule(Long page, Long linit, String hoscode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2 根据工作日workDate期进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //分页
                Aggregation.skip((page - 1) * linit),
                Aggregation.limit(linit)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggregateRes = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregateRes.getMappedResults();

        //TODO
        //分组查询的总记录数
        Aggregation aggregationTotal = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(aggregationTotal, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();
        //日期--->星期
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        //设置最终数据，进行返回
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        res.put("total", total);
        //---其他基础数据
        String hosName = hospitalService.getHospName(hoscode);
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        res.put("baseMap", baseMap);
        return res;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        //TODO 日期DATE---字符串STRING, 转换
        DateTime dateTime = new DateTime(workDate);
        Date date = dateTime.toDate();
//        List<Schedule> scheduleList = scheduleRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode, date);
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, date);
        //TODO 封装参数：把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.stream().forEach(item -> this.packageSchedule(item));
        return scheduleList;
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        // 1、获取：预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (null == hoscode) {
            throw new UnipayException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        // 2、获取：可预约日期，分页数据
        IPage iPage = this.getListDate(page, limit, bookingRule);
        // 3、当前可预，约日期集合
        List<Date> dateList = iPage.getRecords();
        System.out.println("dateList: " + dateList);
        // TODO 4、获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        // 5、合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo。  key->日期、value->预约规则和剩余数量
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            // TODO Vo 转 Map
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(
                    BookingScheduleRuleVo::getWorkDate,
                    BookingScheduleRuleVo -> BookingScheduleRuleVo
            ));
        }
        // 6、根据当前可预约日期集合，获取：可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null == bookingScheduleRuleVo) {
                // 说明：当天没有人排班
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setDocCount(0);
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            // 否则：
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            // 计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            // TODO 最后一页最后一条记录为----即将预约     状态: 0：正常、1：即将放号、-1：当天已停止挂号
            if (i == dateList.size() - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            // TODO 当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopDT = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopDT.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        // 7、可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;

    }

    @Override
    public Schedule getByID(String scheduleId) {
        // Schedule schedule = scheduleRepository.findById(scheduleId).get();
        Optional<Schedule> repositoryById = scheduleRepository.findById(scheduleId);
        if (repositoryById != null && repositoryById.isPresent()) {
            Schedule schedule = repositoryById.get();
            Schedule schedulePac = this.packageSchedule(schedule);
            return schedulePac;
        }
        return null;
    }

    // 获取：可预约日期，分页数据
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        // 1、当天，放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        // 2、预约周期（一般为10天）
        Integer cycle = bookingRule.getCycle();
        // TODO 3、如果：当天放号时间已过，那么下一次预约时间为明天，周期需 +1 天
        if (releaseTime.isBeforeNow()) cycle++;
        // 4、可预约周期中，最后一天显示：放号倒计时！
        List<Date> dateList = new ArrayList<>();
        // 5、计算当前时间的，预约周期
        for (int i = 0; i < cycle; i++) {
            DateTime dateTime = new DateTime().minusYears(2).minusMonths(6).minusDays(2).plusDays(i);
            String dtString = dateTime.toString("yyyy-MM-dd");
            Date date = new DateTime(dtString).toDate();
            dateList.add(date);
        }
        // TODO 6、日期分页（通常，一页仅显示最近7天预约信息）
        // 由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        // 如果：要显示条数小于7，直接显示
        if (end > dateList.size()) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());         //？？？？？？
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /*
        将Date日期（yyyy-MM-dd HH:mm）转换成DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).minusYears(2).minusMonths(6).minusDays(2).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        System.out.println("dateTime: " + dateTime);
        return dateTime;
    }


    //封装schedule参数
    private Schedule packageSchedule(Schedule schedule) {
        Map<String, Object> paramMap = schedule.getParam();
        paramMap.put("hosname", hospitalService.getHospName(schedule.getHoscode()));
        paramMap.put("depname", departmentService.getDepname(schedule.getHoscode(), schedule.getDepcode()));
        //设置: 日期 对应 星期
        paramMap.put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        schedule.setParam(paramMap);
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }


    // 根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        // TODO 1、获取：排班信息
        // Schedule schedule = baseMapper.selectById(scheduleId);
        // Optional<Schedule> scheduleRepositoryById = scheduleRepository.findById(scheduleId);
        // Schedule schedule = scheduleRepositoryById.get();
        // schedule = this.packageSchedule(schedule);
        Schedule schedule = this.getByID(scheduleId);
        // System.out.println(schedule);
        if (schedule == null) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        // 2、获取：预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (null == hospital) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (null == bookingRule) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        // scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepname(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAmount(schedule.getAmount());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());

        // TODO 退号截止天数（如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        // 预约，开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        // 预约，截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        // 当天，停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        // TODO 主键一致，就是更新
        scheduleRepository.save(schedule);
    }
}
